package proTrack.model;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;

@Entity
@NamedQueries({
	@NamedQuery(name = "AllStates", 
			query="SELECT s FROM State s"),
	@NamedQuery(name = "StartStates", 
			query="SELECT s FROM State s WHERE s.predecessors IS EMPTY"),
	@NamedQuery(name = "EndStates", 
			query="SELECT s FROM State s WHERE s.successors IS EMPTY"),
	@NamedQuery(name = "StateByName", 
			query="SELECT s FROM State s WHERE s.name= ?1"),
	@NamedQuery(name = "DeleteState", 
			query="DELETE FROM State s WHERE s.name= ?1"),
			
			
		
})
public class State {

	@ManyToMany(targetEntity=State.class, cascade=CascadeType.ALL)
	private List<State> successors;
	
	@ManyToMany(targetEntity=State.class, cascade=CascadeType.ALL, mappedBy="successors")
	private List<State> predecessors;
	
	@Id
	@GeneratedValue
	private int id;
	
	@Column(unique=true, nullable=false)
	private String name;

	public State() {
		successors = new ArrayList<State>();
		predecessors = new ArrayList<State>();
	}
	
	public State(final String name) {
		this();
		this.name = name;
		
	}
	
	public List<State> getSuccessors() {
		return successors;
	}
	
	public List<State> getPredecessors() {
		return predecessors;
	}
	
	public int getId() {
		return id;
	}

	public void setId(final int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(final String name) {
		this.name = name;
	}
	
	public void addSuccessor(final State state, final int position) {
		int pos = position;
		int size = successors.size();
		if (pos < 0 || pos >= size) {
			pos = size;
		}
		successors.add(pos, state);
		state.predecessors.add(this);
	}
	
	@Override
	public String toString() {
		return getName()+ " " + toString(successors) + " " + toString(predecessors);
	}

	private String toString(final List<State> list) {
		StringBuilder b = new StringBuilder("[");
		for (State s : list) {
			b.append(" ").append(s.getName()).append(" ");
		}
		
		b.append("]");
		return b.toString();
	}

    

}
